const { User, Role, Permission } = require('../models')
const jwt = require('jsonwebtoken')

// 权限检查中间件
const checkPermission = (requiredPermission) => {
  return async (ctx, next) => {
    try {
      const userId = ctx.state.user.userId

      // 获取用户及其角色权限
      const user = await User.findByPk(userId, {
        include: [{
          model: Role,
          as: 'roles',
          include: [{
            model: Permission,
            as: 'permissions',
            through: { attributes: [] }
          }],
          through: { attributes: [] }
        }]
      })

      if (!user || user.status !== 'active') {
        ctx.status = 401
        ctx.body = {
          success: false,
          message: '用户状态异常'
        }
        return
      }

      // 收集所有权限
      const userPermissions = []
      user.roles.forEach(role => {
        role.permissions.forEach(permission => {
          if (!userPermissions.includes(permission.code)) {
            userPermissions.push(permission.code)
          }
        })
      })

      // 检查是否有超级管理员角色
      const isSuperAdmin = user.roles.some(role => role.code === 'super_admin')
      
      // 超级管理员跳过权限检查，或者用户拥有所需权限
      if (isSuperAdmin || userPermissions.includes(requiredPermission)) {
        await next()
      } else {
        ctx.status = 403
        ctx.body = {
          success: false,
          message: '权限不足',
          requiredPermission
        }
      }
    } catch (error) {
      console.error('Permission check error:', error)
      ctx.status = 500
      ctx.body = {
        success: false,
        message: '权限验证失败'
      }
    }
  }
}

// 角色检查中间件
const checkRole = (requiredRole) => {
  return async (ctx, next) => {
    try {
      const userId = ctx.state.user.userId

      const user = await User.findByPk(userId, {
        include: [{
          model: Role,
          as: 'roles',
          through: { attributes: [] }
        }]
      })

      if (!user || user.status !== 'active') {
        ctx.status = 401
        ctx.body = {
          success: false,
          message: '用户状态异常'
        }
        return
      }

      const userRoles = user.roles.map(role => role.code)
      
      if (userRoles.includes('super_admin') || userRoles.includes(requiredRole)) {
        await next()
      } else {
        ctx.status = 403
        ctx.body = {
          success: false,
          message: '角色权限不足',
          requiredRole
        }
      }
    } catch (error) {
      console.error('Role check error:', error)
      ctx.status = 500
      ctx.body = {
        success: false,
        message: '角色验证失败'
      }
    }
  }
}

// JWT token 验证中间件
const authenticateToken = async (ctx, next) => {
  try {
    const authHeader = ctx.headers.authorization
    const token = authHeader && authHeader.split(' ')[1]

    if (!token) {
      ctx.status = 401
      ctx.body = {
        success: false,
        message: '访问令牌缺失'
      }
      return
    }

    // 验证JWT token
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'xSynergyOs_JWT_Secret_Key_2024')
    
    // 获取用户详细信息和权限
    const user = await User.findByPk(decoded.userId, {
      include: [{
        model: Role,
        as: 'roles',
        include: [{
          model: Permission,
          as: 'permissions',
          through: { attributes: [] }
        }],
        through: { attributes: [] }
      }]
    })

    if (!user || user.status !== 'active') {
      ctx.status = 401
      ctx.body = {
        success: false,
        message: '用户不存在或已禁用'
      }
      return
    }

    // 收集所有权限
    const userPermissions = []
    user.roles.forEach(role => {
      role.permissions.forEach(permission => {
        if (!userPermissions.includes(permission.code)) {
          userPermissions.push(permission.code)
        }
      })
    })

    // 设置用户信息到 ctx.state
    ctx.state.user = {
      userId: user.id,
      username: user.username,
      permissions: userPermissions,
      roles: user.roles.map(role => role.code)
    }

    await next()
  } catch (error) {
    console.error('Token verification error:', error)
    ctx.status = 401
    ctx.body = {
      success: false,
      message: '访问令牌无效'
    }
  }
}

module.exports = {
  requirePermission: checkPermission,
  requireRole: checkRole,
  checkPermission,
  checkRole,
  authenticateToken
}